package com.wang.code;	
public class _4LinkedListDemo {
	private Node first;
	private int size;
	
	public _4LinkedListDemo() {
	}
	public _4LinkedListDemo(Object obj){
		add(obj);
	}
	public void add(Object obj){
		Node node = new Node(obj);
		if (first == null) {
			first = node;
		} else {
			Node temp = first;
			while (temp.next != null) {
				temp = temp.next;
			}
			temp.next = node;
		}
		size++;
	}
	public String toString() {
		StringBuilder sb = new StringBuilder("[");
		if (size == 0) {
			return sb.append("]").toString();
		}
		Node temp = first;
		
		for (int i = 0; i <= size-2; i++) {
			sb.append(temp.value).append(",");
			temp = temp.next;
		}
		return sb.append(temp.value).append("]").toString();
	}
	private void checkIndex(int index)throws IllegalArgumentException {
		if (index > size-1 || index < 0) {
			throw new IllegalArgumentException("请注意，下标范围：[0," + (size-1) + "]");//非法参数异常，给调用者提示
		}
	}
	private Node searchNodeByIndex(int index) throws IllegalArgumentException{
		checkIndex(index);
		Node temp = first;
		for (int i = 0; i < index; i++) {
			temp = temp.next;
		}
		return temp;
	}
	
	public Object searchByIndex(int index) throws IllegalArgumentException{
		Node node = searchNodeByIndex(index);
		return node.value;
	}
	public int searchByElement(Object ele){
		if (first == null) {
			return -1;
		}
		if (ele == null) {
			Node temp = first;
			for (int i = 0; i < size; i++) {
				if (ele == temp.value) {
					return i;
				}
				temp = temp.next;
			}
		} else {
			Node temp = first;
			for (int i = 0; i < size; i++) {
				if (ele.equals(temp.value)) {
					return i;
				}
				temp = temp.next;
			}
		}
		return -1;
	}
	public void updateByIndex(int index,Object obj) throws IllegalArgumentException{
		checkIndex(index);
		Node node = searchNodeByIndex(index);
		node.value = obj;
	}
	
	
	public Object deleteByIndex(int index) throws IllegalArgumentException{
		checkIndex(index);
		Node now = null;
		if (index == 0) {
			now = first;
			first = first.next;
		} else {
			Node prefix = searchNodeByIndex(index-1);
			now = searchNodeByIndex(index);
			prefix.next = now.next;
		} 
		size--;
		return now.value;
	}
	public void deleteByElement(Object ele) throws IllegalArgumentException{
		int index = searchByElement(ele);
		if (index < 0) {
			return;
		}
		deleteByIndex(index);
	}
	public void insertByIndex(int index,Object obj) throws IllegalArgumentException{
		checkIndex(index);
		Node node = new Node(obj);
		if (index == 0) {
			node.next = first;
			first = node;
		} else {
			Node prefix = searchNodeByIndex(index-1);
			Node now = searchNodeByIndex(index);
			node.next = now;
			prefix.next = node;
		} 
		size++;
	}
	
	public void clear(){
		first = null;
		size = 0;
	}
	
	public int size(){
		return size;
	}
	
	private class Node{
		Object value;
		Node next;
		public Node(Object value) {
			super();
			this.value = value;
		}
	}
}
